import { defineComponent, onMounted, reactive } from "vue";
import styles from "./bindMobile.module.less";
import { $captcha } from "@/api/captcha/captcha";
import { useStore as useUserStore } from "@/store/user";
import { useStore as useInfoStore } from "@/store/userinfo";
import useSmsRefund from "@/hooks/useSmsRefund";
import { message } from "ant-design-vue";
import validateInstance from "@/libs/validate/validate";
import { $modifyMobile } from "@/api/account/account";
import { useRouter } from "vue-router";
export default defineComponent({
  name:'accountUserinfoBindMobilePhoneBindMobile',
  setup() {
    const userStore = useUserStore();
    const infoStore = useInfoStore();
    const smsRefund = useSmsRefund();
    const router = useRouter();
    const state = reactive({
      current: 1,
      steps: [
        {
          title: '验证身份',
        },
        {
          title: '绑定手机号'
        },
        {
          title: '完成'
        }
      ],
      img_one: '',
      img_two: '',
      form: {
        newMobile: '',
        code_two: '',
        syncCode_two: '',
      },
      level: [],
      btn_text: '下一步',
    } as any)
    //获取图形验证码
    const requestCode = () => {
      $captcha({}).then((res: any) => {
        state.img_two = res.data.img;
      })
    }

    //获取短信验证码
    const sendMobileCode = () => {
      let param = {
        mobile: state.form.newMobile,
        captcha: state.form.code_two,
        scene: 'user.modifyMobile',
      }
      smsRefund.sendSms(param);
    }


    const newMobile_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入新手机号')
      } else if (!validateInstance.test(value, "phone")) {
        return Promise.reject('手机号格式不正确!');
      }
    }

    const code_two_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入图形验证码')
      }
    }

    const syncCode_two_check = async (_rule: any, value: string) => {
      if (value === '') {
        return Promise.reject('请输入短信验证码')
      }
    }

    //表单验证
    const submitRules = {
      newMobile: [{ required: true, validator: newMobile_check, trigger: 'change' }],
      code_two: [{ required: true, validator: code_two_check, trigger: 'change' }],
      syncCode_two: [{ required: true, validator: syncCode_two_check, trigger: 'change' }]
    }

    //下一步
    const nextStep = () => {
      if (!state.form.newMobile) {
        message.error('请输入手机号');
        return;
      }
      if (!(state.form.code_two && state.form.syncCode_two)) {
        message.error('请输入验证码');
        return;
      }
      $modifyMobile({
        code: state.form.syncCode_two,
        mobile: state.form.newMobile,
        flag: infoStore.mobileFlag,
      }).then((res: any) => {
        infoStore.clearPasswordFlag();
        state.current = 2;
      }).catch((error: any) => {
        if (error.code === 403) { //验证标记失效或者不正确处理
          message.error('验证信息已失效，请重新验证身份');
          router.go(-1);
        }
      })
    }
    onMounted(() => {
      requestCode();
      if (!infoStore.mobileFlag) {
        message.error('验证信息已失效，请重新验证身份');
        router.go(-1);
        return;
      }
      state.form.mobile = userStore.user_info.mobile;
    })
    return () => (
      <div class={styles.AccountSecurityLayout}>
        <div class={styles.header}>绑定手机号</div>
        <div class={styles.container}>
          <a-steps current={state.current}>
            <a-step title={'验证身份'}></a-step>
            <a-step title={'绑定手机号'}></a-step>
            <a-step title={'完成'}></a-step>
          </a-steps>
          <div class={styles['form-box']}>
            {
              <a-form model={state.form} v-show={state.current === 1} rules={submitRules} label-col={{ style: { width: '90px' } }}>
                <a-form-item required label="新手机号" name="newMobile">
                  <a-input style={{ width: '210px' }} v-model:value={state.form.newMobile} maxlength={11} />
                </a-form-item>
                <div style={{ display: 'flex' }}>
                  <a-form-item required label="图形验证码" name="code_two">
                    <a-input style={{ width: '150px' }} v-model:value={state.form.code_two} maxlength={4} />
                  </a-form-item>
                  <a-form-item wrapper-col={{ span: 5 }}>
                    <div class={styles['code-img']}>
                      <img src={state.img_two} onClick={() => { requestCode() }} />
                    </div>
                  </a-form-item>
                </div>
                <div style={{ display: 'flex' }}>
                  <a-form-item required label="短信验证码" name="syncCode_two">
                    <a-input style={{ width: '150px' }} v-model:value={state.form.syncCode_two} maxlength={6} />
                  </a-form-item>
                  <a-form-item wrapper-col={{ span: 5 }}>
                    <div class={[styles['send-btn']]} onClick={() => { sendMobileCode() }}>{smsRefund.show_text.value}</div>
                  </a-form-item>
                </div>
              </a-form>
            }
            {
              <div class={styles.success} v-show={state.current === 2}>
                <span>手机号更新成功</span>
              </div>
            }
            <div class={styles['nextStep-btn']} onClick={() => { nextStep() }} v-show={state.current !== 2}>{state.btn_text}</div>
          </div>
        </div>
      </div>
    )
  }
})